<?php

namespace App\Admin\Controller\Base;

use App\Admin\Service\Base\DefaultLoginService;
use App\Admin\Service\Base\LoginAccountService;
use App\Common\Exception\ApiMessageException;
use App\Common\Util\AdminAuth;
use App\Common\Util\Response;
use App\Common\Util\TP;
use think\facade\Cookie;
use think\response\Redirect;

/**
 * Class LoginController
 */
class LoginController
{
    /**
     * 登录页面
     *
     * @return string
     * @throws \Exception
     */
    public function loginView(): string
    {
        $authSign          = TP::request()->get('auth', '');
        $adminLoginService = LoginAccountService::getLoginService($authSign);

        Cookie::set('auth', $authSign);

        return Response::render($adminLoginService->loginView());
    }


    /**
     * 登录
     *
     * @return \think\Response
     * @throws ApiMessageException
     */
    public function loginIn()
    {
        try {
            $adminLoginService = LoginAccountService::getLoginService(TP::request()->get('auth', ''), true);
        } catch (\Throwable $throwable) {
            throw new ApiMessageException($throwable->getMessage());
        }
        $adminLoginService->login(TP::request()->post());
        op_log(AdminAuth::getInfo()->name ." 登录,IP:" . TP::request()->ip());
        $url = TP::route()->to([IndexController::class, 'index']);

        return Response::json()->success([
            'redirect' => $url->url()
        ]);
    }

    /**
     * 退出登录
     *
     * @return \think\Response|Redirect
     * @throws \Exception
     */
    public function loginOut(): \think\Response|Redirect
    {
        if (LoginAccountService::isNormalLogin()) {
            op_log(AdminAuth::getInfo()->name ." 退出登录");
            AdminAuth::clear();
        }else{
            LoginAccountService::quitAccount();
        }

        return Response::redirect(TP::route()->to([IndexController::class, 'index']));
    }
}